package com.hl.mystudy.ui.home.ui.aidl;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.IntentCompat;
import androidx.databinding.DataBindingUtil;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;

import com.hl.mystudy.IMyAidlInterface;
import com.hl.mystudy.R;
import com.hl.mystudy.databinding.ActivityAidlGuestBinding;
import com.hl.mystudy.util.LogUtil;
import com.hl.mystudy.util.ToastUtil;

public class AidlGuestActivity extends AppCompatActivity {

    private ServiceConnection conn;
    private IMyAidlInterface manager;

    private ActivityAidlGuestBinding mBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_aidl_guest);
        conn = getServiceConnetion();
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.hl.mystudy", "com.hl.mystudy.ui.home.ui.aidl.MyAidlService"));
        bindService(intent, conn, BIND_AUTO_CREATE);

        mBinding.btnAidlGetName.setOnClickListener(v -> {
            LogUtil.i("获取名字:");
            try {
                ToastUtil.showToastShort(this, manager.getName() + "");
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        });

        mBinding.btnAidlLog.setOnClickListener(v -> {
            LogUtil.i("打印日志:");

            try {
                manager.sayHello("aaaaaaaaaaaaaaaaaaaaaaa");
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
        });


    }

    private ServiceConnection getServiceConnetion() {
        return new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                manager = IMyAidlInterface.Stub.asInterface(service);
                LogUtil.i("链接成功");
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                LogUtil.i("链接失败");
            }
        };
    }
}